<?php

namespace app\api\model;

use think\Db;
use think\Model;

/**
 * 模型
 */
class OrderAdd extends Model
{
    // 表名
    protected $name = 'shop_order_add';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    public static function objectToArray($object) {
        $jsonString = json_encode($object);
        $array = json_decode($jsonString, true);

        return $array;
    }

    /**
     * @ DateTime 2021-06-01
     * @ 订单结算
     * @param string $order_sn      订单号
     * @param float  $payamount     支付金额
     * @param string $transactionid 流水号
     * @return bool
     */
    public static function settle($order_sn, $payamount, $transactionid = '',$paytype)
    {
        $order = self::with(['orderGoods'])->where('order_sn', $order_sn)->find();

        //dump($order->order_goods);die;
        if (!$order || $order->paystate == 1) {
            return false;
        }

        if ($payamount != $order->saleamount) {
            \think\Log::write("[shop][pay][{$order_sn}][订单支付金额不一致]");
            return false;
        }

        // 启动事务
        Db::startTrans();
        try {
            $order->paystate = 1;
            $order->transactionid = $transactionid;
            $order->payamount = $payamount;
            $order->paytime = time();
            $order->paytype = $paytype;

            $order->save();
            if ($order->payamount == $order->saleamount) {
                //支付完成后,商品销量+1
                foreach ($order->order_goods as $item) {
                    $goods = $item->goods;
                    $sku = $item->sku;
                    if ($goods) {
                        $goods->setInc('sales', $item->nums);
                    }
                    if ($sku) {
                        $sku->setInc('sales', $item->nums);
                    }
                }
            }
            //将新增餐品的信息同步到父级订单
            $parent_order_id = $order->parent_order_id;
            $parent_order_detail = Order::get($parent_order_id);
            $order_goods_list = $order->order_goods;


            foreach ($order_goods_list as $k=>$v){
                $v = self::objectToArray($v);

                unset($v['id']);
                $order_goods_model = new OrderGoods();
                /*$v['order_sn'] = $parent_order_detail->order_sn;
                $v['order_id'] = $parent_order_detail->id;
                $order_goods_data = $v;*/
                $order_goods_data = [
                    'order_sn'=>$parent_order_detail->order_sn,
                    'order_id'=>$parent_order_detail->id,
                    'goods_sn'=>$v['goods_sn'],
                    'goods_id'=>$v['goods_id'],
                    'goods_sku_id'=>$v['goods_sku_id'],
                    'title'=>$v['title'],
                    'nums'=>$v['nums'],
                    'marketprice'=>$v['marketprice'],
                    'price'=>$v['price'],
                    'realprice'=>$v['realprice'],
                    'attrdata'=>$v['attrdata'],
                    'image'=>$v['image'],
                ];
                $res = $order_goods_model->save($order_goods_data);

            }

            //修改原始订单的金额
            $parent_order_detail->discount+=$order->discount;
            $parent_order_detail->saleamount+=$order->saleamount;
            $parent_order_detail->payamount+=$order->payamount;
            $parent_order_detail->goodsprice+=$order->goodsprice;
            $parent_order_detail->amount+=$order->goodsprice;
            $parent_order_detail->save();

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        //记录操作


        return true;
    }



    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function orderGoods()
    {
        return $this->hasMany('OrderGoodsAdd', 'order_sn', 'order_sn');
    }
}